'use strict';
/**
 * @Controller email
 */
const Controller = require('egg').Controller;

class EmailController extends Controller {

   /**
    * @summary 发送邮箱验证码
    * @description 发送邮箱验证码
    * @router post ppyy/email
    * @request query integer title 验证标题
    * @response 200 JsonResult 操作结果
    */
  async postEmail() {
    const { ctx, service } = this;

    let { title, email } = ctx.request.body;
    let subject = title || 'ppyy日记';
    let verifyStr = await service.tool.verifyStr();
    let html = `
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ppyy日记验邮箱证码</title>
</head>
<body>
    <h1 style="">有问题也可添加官方QQ：1172824156</h1>
    <div>提示： 验证码很长请复制完全, 验证码有效时间5分钟</div>
    <div>ppyy日记的验证码：</div>
    <h1 style=""><u> ${verifyStr} </u></h1>
</body>
</html>`
    let emailOk = await service.tool.sendMail(email, subject, html);
    let obj;
    let time;
    if(emailOk) {
      if(title && title == 'reg') {
        obj = { code: 200, data: verifyStr }
      } else {
        obj = { code: 200, msg: '发送成功' }
        let updata = await ctx.model.Users.updateOne({email}, { reg: verifyStr });
        if(updata.ok != 1) obj = { code: 201, msg: '发送验证码失败' }
        clearTimeout(time);
        time = setTimeout(async ()=> {
          await ctx.model.Users.updateOne({email}, { reg: '' });
        }, 1000 * 60 * 1);
      }
    } else {
      obj = { code: 201, msg: '发送验证码失败' }
    }
    ctx.body = obj
  }
}

module.exports = EmailController;
